using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;


namespace SsisUtilities.PacMan.Components
{
    public class SlnHelper
    {
        public static List<FileInfo> GetProjects(FileInfo solutionFile)
        {
            DirectoryInfo solutionFolder = solutionFile.Directory;

            List<FileInfo> projectList = new List<FileInfo>();
            
            using (StreamReader sr = solutionFile.OpenText()) 
            {
                while (sr.Peek() >= 0) 
                {
                    string solutionLine = sr.ReadLine();

                    if (solutionLine.StartsWith("Project"))
                    {
                        // this line identifies a project in the solution file
                        int dtprojPosition = solutionLine.IndexOf(".dtproj");
                        if (dtprojPosition > 0)
                        {
                            // the project is an SSIS project
                            int projectStartPosition = solutionLine.LastIndexOf(
                                "\"", dtprojPosition, dtprojPosition) + 1;
                            string projectFilePath = solutionLine.Substring(
                                projectStartPosition,
                                (dtprojPosition + 7) - projectStartPosition);
                            System.Diagnostics.Debug.WriteLine(solutionFolder.FullName +
                                @"\" + projectFilePath);
                            projectList.Add(new FileInfo(solutionFolder.FullName +
                                @"\" + projectFilePath));
                        }
                    }
                }
            }

            return projectList;
        }

        public static List<FileInfo> GetPackageFiles(FileInfo solutionFile)
        {
            List<FileInfo> projectList = GetProjects(solutionFile);

            List<FileInfo> packageList = new List<FileInfo>();

            foreach (FileInfo projectFile in projectList)
            {
                packageList.AddRange(DtprojHelper.GetPackageFiles(projectFile));
            }

            return packageList;
        }

        public static List<PackageUtil> GetPackageUtils(FileInfo solutionFile)
        {
            List<FileInfo> projectList = GetProjects(solutionFile);

            List<PackageUtil> packages = new List<PackageUtil>();

            foreach (FileInfo projectFile in projectList)
            {
                packages.AddRange(DtprojHelper.GetPackageUtils(projectFile));
            }

            return packages;
        }
    }
}
